﻿using Chloe;
using DotNetEx;
using Mrc.AuthService.IService;
using Mrc.DBContext;
using Mrc.Entities;
using Mrc.Entity;
using Surging.Core.CPlatform.Ioc;
using Surging.Core.ProxyGenerator;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Mrc.AuthService.Service
{
    /// <summary>
    /// 登录检测
    /// </summary>
    [ModuleName("AccountLogon")]
    public class AccountLogonService : ProxyServiceBase, IAccountLogonService
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginName">账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
      public  Task<SysUser> CheckLogon(string loginName, string password)
      {         
            return Task.Run(() => {
                var result = new SysUser();//AjaxResult.CreateResult<SysUser>(ResultStatus.Failed, new SysUser());
                using (var DbContext = DbContextHelper.GetDBContext())
                {
                    try
                    {
                        if (loginName.IsNullOrEmpty() || password.IsNullOrEmpty())
                            throw new Exception("登录名或密码不能为空");
                        var view = DbContext.JoinQuery<SysUser, SysUserLogOn>((u, userLogOn) => new object[]
                        {
                        JoinType.InnerJoin,u.Id == userLogOn.UserId
                        })
                        .Select((u, userLogOn) => new { User = u, UserLogOn = userLogOn });
                        loginName = loginName.ToLower();
                        if (MrcUtils.IsMobilePhone(loginName))
                        {
                            view = view.Where(a => a.User.MobilePhone == loginName);
                        }
                        else if (MrcUtils.IsEmail(loginName))
                        {
                            view = view.Where(a => a.User.Email == loginName);
                        }
                        else
                        {
                            view = view.Where(a => a.User.AccountName == loginName);
                        }

                        view = view.Where(a => a.User.State != AccountState.Closed);

                        var viewEntity = view.FirstOrDefault();

                        if (viewEntity == null)
                        {
                            throw new Exception("账户不存在，请重新输入");
                        }
                        if (viewEntity.User.State == AccountState.Disabled)
                        {
                            throw new Exception("账户被禁用，请联系管理员");
                        }
                        SysUser userEntity = viewEntity.User;
                        SysUserLogOn userLogOnEntity = viewEntity.UserLogOn;
                        string dbPassword = EncryptHelper.EncryptMD5Password(password, userLogOnEntity.UserSecretkey);
                        if (dbPassword != userLogOnEntity.UserPassword)
                        {
                            throw new Exception("密码不正确，请重新输入");
                        }
                        DateTime lastVisitTime = DateTime.Now;
                        DbContext.Update<SysUserLogOn>(a => a.Id == userLogOnEntity.Id, a => new SysUserLogOn() { LogOnCount = a.LogOnCount + 1, PreviousVisitTime = userLogOnEntity.LastVisitTime, LastVisitTime = lastVisitTime });
                        result = userEntity;
                        //result.Data = userEntity;
                        //result.status = ResultStatus.OK;
                    }
                    catch (Exception ex)
                    {
                       // result.msg = ex.Message;
                    }
                }
                return result;
            });
      }        
    }
}
